import axios from "axios";
import Vue from "vue";
import router from "@/router";
import { clearLoginInfo } from "@/utils";

const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  }
});

/**
 * 请求拦截，每次携带token
 */
http.interceptors.request.use(
  config => {
    config.headers["token"] = Vue.cookie.get("token");
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

/**
 * 响应拦截,状态码为401则需重新登录
 */
http.interceptors.response.use(
  response => {
    if (response.data && response.data.code === 401) {
      // 401, token失效
      clearLoginInfo();
      router.push({ name: "login" });
    }
    return response;
  },
  error => {
    return Promise.reject(error);
  }
);

export default http;
